var http = require('http');
var exec = require('shelljs').exec;

const PORT = 6603;

console.log('listening port at: ' + PORT);

const cmds = {
    '/api/deploy': 'git pull && npm start',
};

console.log(cmds);

const deployServer = http.createServer(function(request, response) {

    let inCMDs = false;
    let cmd = '';

    for(var key in cmds) {
        if(key === request.url) {
            inCMDs = true;
            cmd = cmds[key];
            break;
        }
    }

    if(inCMDs) {
        exec(cmd, function(err, out, code) {
            if(err instanceof Error) {
                response.writeHead(500);
                response.end('Server Internal Error.');
                throw err;
            }
            process.stderr.write(err.toString());
            process.stdout.write(out.toString());
            response.writeHead(200);
            response.end('Deploy Done.');
        });
    }
    else {
        response.writeHead(404);
        response.end('Invalid Deploy Request');
    }

});

deployServer.listen(PORT);
